package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.fagin.ApAuthorFagin;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.AdPageUserDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.fagin.WmUserFagin;
import com.itheima.wemedia.pojo.WmUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Service

public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    //注入user的mapper（持久层）
    @Autowired
    private ApUserMapper apUserMapper;

    //注入fagin对象
    @Autowired
    private WmUserFagin wmUserFagin;

    @Autowired
    private ApAuthorFagin apAuthorFagin;
    @Override
    public PageResultVo pageList(AdPageUserDto adPageUserDto) {
        //创建分页条件对象
        IPage<ApUserRealname> iPage = new Page<>(adPageUserDto.getPage(),adPageUserDto.getSize());
        //创建查询条件对象
        LambdaQueryWrapper<ApUserRealname> lwq = new LambdaQueryWrapper<>();
        //构建查询条件
        lwq.eq(adPageUserDto.getStatus()!=null,ApUserRealname::getStatus,adPageUserDto.getStatus());
        //进行分页查询
        page(iPage,lwq);
        //对查询到的参数封装并返回
        return PageResultVo.pageResult(adPageUserDto.getPage(),adPageUserDto.getSize(),iPage.getTotal(),iPage.getRecords());
    }

    @Override
    public boolean authFail(Map<String, Object> authMap) {
        //获取前端传过来的id和驳回信息
        Integer id = (Integer) authMap.get("id");
        String msg = (String)(authMap.get("msg"));
        //构建一个新的对象进行对数据表的修改
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(id.longValue());
        apUserRealname.setReason(msg);
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        apUserRealname.setUpdatedTime(LocalDateTime.now());
        return updateById(apUserRealname);
    }

    @Override
    @Transactional(rollbackFor = LeadNewsException.class)
    public void authPass(Map<String, Object> authMap) {
        //获取前端传过来的参数
        Integer id =(Integer) authMap.get("id");
        //查询实名认证表获取实名认证对象
        ApUserRealname byId = getById(id);
        //获取用户id
        Long userId = byId.getUserId();
        //认证通过通过远程调用wemedia微服务查询用户id是否有存储
        Long wmUserId = findWmUser(userId);
        //自媒体创建账号成功，创建作者对象
        addArticle(userId,wmUserId,byId);
        //创建一个实名认证对象
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(id.longValue());
        apUserRealname.setUpdatedTime(LocalDateTime.now());
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        updateById(apUserRealname);
        //创建user对象,根据对象对user进行数据库的修改
        ApUser apUser = new ApUser();
        apUser.setId(userId);
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        apUserMapper.updateById(apUser);
    }

    /**
     * 作者对象创建业务代码
     * @param userId 用户id
     * @param wmUserId 自媒体id
     */
    private void addArticle(Long userId, Long wmUserId,ApUserRealname byId) {
        //根据用户id远程调用作者微服务查询作者对象
        ResultVo<ApAuthor> result = apAuthorFagin.findById(userId,wmUserId);
        //判断查询作者是否成功,失败则抛出异常，回滚数据
        if (!result.isSuccess()){
            log.error("调用作者查询服务失败"+userId);
            throw new LeadNewsException("调用作者查询服务失败！");
        }
        //获取查询到的apAuthor对象
        ApAuthor apAuthor = result.getData();
        //判断查询数据是否为空，为空则进行创建对象
        if (apAuthor==null){
            //创建一个作者对象
            ApAuthor newApAuthor = new ApAuthor();
            newApAuthor.setName(byId.getName());
            newApAuthor.setCreatedTime(LocalDateTime.now());
            newApAuthor.setUserId(userId);
            newApAuthor.setWmUserId(wmUserId);
            newApAuthor.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            //远程调用执行添加操作
            ResultVo<ApAuthor> resultVo = apAuthorFagin.addWmUser(newApAuthor);
            //判断是否添加作者成功，不成功则抛出异常
            if (!resultVo.isSuccess()){
                log.error("调用作者添加服务失败"+userId);
                throw new LeadNewsException("调用作者添加服务失败！");
            }
        }
    }

    /**
     * 自媒体创建查询业务代码
     * @param userId 用户id
     * @return 返回自媒体Id
     */
    private Long findWmUser(Long userId) {
        //调用WmUserFagin对象查询
        ResultVo<WmUser> result = wmUserFagin.findUserById(userId);
        //判断是否查询自媒体的数据库成功，不成功则进行事务回滚
        if (!result.isSuccess()){
            log.error("调用自媒体查询服务失败"+userId);
            throw new LeadNewsException("调用自媒体查询服务失败！");
        }
        //获取返回的对象
        WmUser wmUser = result.getData();
        //判断wmUser是否为空，为空则创建一个自媒体账号
        if (wmUser==null){
            //创建一个自媒体对象
            WmUser newWmUser = new WmUser();
            //查询数据库获取user对象
            ApUser apUser = apUserMapper.selectById(userId);
            //将查询到的user对象中相同的数据拷贝到wmUser对象中
            BeanUtils.copyProperties(apUser,newWmUser);
            newWmUser.setId(null);
            newWmUser.setApUserId(userId);
            newWmUser.setCreatedTime(LocalDateTime.now());
            newWmUser.setNickname(apUser.getName());
            newWmUser.setScore(0);
            newWmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            newWmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            //远程调用进行添加数据
            ResultVo<WmUser> resultVo = wmUserFagin.addWmUser(newWmUser);
            //判断返回数据是否添加成功，不成功则抛出异常进行回滚操作
            if (!resultVo.isSuccess()){
                log.error("调用自媒体创建服务失败"+userId);
                throw new LeadNewsException("调用自媒体创建服务失败！");
            }
            wmUser = wmUserFagin.findUserById(userId).getData();
        }
        return wmUser.getId();
    }
}
